package com.pacifico.telebusca.web.controladores;

import java.sql.SQLException;

import javax.persistence.PersistenceException;

import org.hibernate.JDBCException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.ldap.CommunicationException;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.pacifico.telebusca.exception.Errores;

@Controller
@ControllerAdvice
public class ControladorError {

	@ExceptionHandler({DataIntegrityViolationException.class,Exception.class,SQLException.class,DataAccessException.class})
	public ModelAndView handleAllException(Exception ex) {
		
		boolean isGeneric = Boolean.FALSE;		
		ModelAndView model = new ModelAndView("error");
		String mensajeError = null;
		
		if(ex instanceof PersistenceException){
			System.out.println("PersistenceException " + ex.getMessage());
		}
		if(ex instanceof DataAccessException){
			System.out.println("DataAccessException " + ex.getMessage());
		}
		if(ex instanceof SQLException){
			System.out.println("SQLException " + ex.getMessage());
		}
		if(ex instanceof JDBCException){
			System.out.println("JDBCException " + ex.getMessage());
		}
		if(ex instanceof CannotCreateTransactionException){
			System.out.println("CannotCreateTransactionException " + ex.getMessage());
		}
		
		if(ex instanceof RuntimeException){
			System.out.println("RuntimeException " + ex.getMessage());
		}
		
		if(ex instanceof java.net.UnknownHostException){
			System.out.println("RuntimeException " + ex.getMessage());
		}
		
		if(ex instanceof CommunicationException){
			System.out.println("CommunicationException " + ex.getMessage());
		}
		if(ex instanceof DataIntegrityViolationException){
			System.out.println("CommunicationException " + ex.getMessage());
		}
		
		if (!isGeneric){
			if(ex instanceof Exception){
				if (ex.getMessage().contains("method 'POST' not supported")){
					mensajeError = Errores.MAP.get("E1001");
				}
				
			}	
		}
		
		
		model.addObject("error", mensajeError);
		return model;
 
	}
	
	
	
}
